package com.rongshu.view.home.fragment;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.AdapterListener;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.home.contract.PenPalView;
import com.rongshu.view.home.entity.PenpalHomeResponse;
import com.rongshu.view.home.presenter.PenpalPresenter;
import com.rongshu.view.penpal.activity.PostDetailsActivity;
import com.rongshu.view.penpal.adapter.PenpalAdapter;
import com.rongshu.view.penpal.adapter.PenpalRecommendArticleAdapter;
import com.rongshu.view.penpal.bean.PenpalRecommendArticleResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2018/11/20.
 * description：笔友会首页
 */
public class PenpalFragment extends BaseFragment<PenpalPresenter> implements PenPalView {
    @BindView(R.id.middle_text)
    TextView middleTv;
    @BindView(R.id.penpal_list)
    RecyclerView penpalList;
    @BindView(R.id.article_list)
    RecyclerView articleList;
    @BindView(R.id.refresh_view)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.search_content)
    RelativeLayout searchContent;
    private int articlePageIndex = 1;
    private int articlePageSize = 10;
    private List<PenpalHomeResponse.ResponseBean.RecommendPenpalwillBean> list;
    private List<PenpalRecommendArticleResponse.ResponseBean> articles;
    private PenpalAdapter penpalAdapter;
    private PenpalRecommendArticleAdapter articleAdapter;
    private int clickPosition;
    private int ITEM_POSITION_REQUEST_CODE = 1001;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_penpal;
    }

    @Override
    protected void initViews() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) searchContent.getLayoutParams();
        layoutParams.topMargin = DensityUtil.getStateBar(getActivity());
        searchContent.setLayoutParams(layoutParams);

        refreshLayout.setEnableAutoLoadmore(false);
        list = new ArrayList<>();
        LinearLayoutManager penpalManager = new LinearLayoutManager(getActivity());
        penpalManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        penpalList.setLayoutManager(penpalManager);
        penpalAdapter = new PenpalAdapter(getActivity(), list);
        penpalList.setAdapter(penpalAdapter);

        articles = new ArrayList<>();
        LinearLayoutManager articleManager = new LinearLayoutManager(getActivity());
        articleList.setLayoutManager(articleManager);
        articleAdapter = new PenpalRecommendArticleAdapter(getActivity(), articles);
        articleList.setAdapter(articleAdapter);
        articleAdapter.setAdapterListener(new AdapterListener() {
            @Override
            public void callBack(Object object) {
                clickPosition = (int) object;
                if (clickPosition >= articles.size()) return;
                Intent intent = new Intent();
                if (articles.get(clickPosition).getContribute_id() == 0) {
                    intent.setClass(getActivity(), PostDetailsActivity.class);
                    intent.putExtra(Constant.POST_ID, articles.get(clickPosition).getTopic_id());
                    startActivityForResult(intent, ITEM_POSITION_REQUEST_CODE);
                } else {
                    intent.setClass(getActivity(), SingleArticleDetailsActivity.class);
                    intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, convertBean(articles.get(clickPosition)));
                    intent.putExtra(Constant.INTENT_STATE, true);
                    startActivityForResult(intent, ITEM_POSITION_REQUEST_CODE);
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                articlePageIndex = 1;
                refreshlayout.resetNoMoreData();
                if (list.size() == 0) {
                    presenter.getRecommendPenpalList();
                }
                presenter.getAriticleList(articlePageIndex, articlePageSize);
                refreshlayout.finishRefresh(5000, false);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                articlePageIndex++;
                presenter.getAriticleList(articlePageIndex, articlePageSize);
                refreshlayout.finishLoadmore(5000, false);//传入false表示刷新失败
            }
        });
    }

    private ArticleDetaisRequest convertBean(PenpalRecommendArticleResponse.ResponseBean response) {
        ArticleDetaisRequest bean = new ArticleDetaisRequest();
        bean.setContribute_id(response.getContribute_id());
        bean.setType(Constant.FROM_PENPAL);
        bean.setTopic_id(response.getTopic_id());
        return bean;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == ITEM_POSITION_REQUEST_CODE) {
            int likeCount = data.getIntExtra(Constant.LIKE_COUNT, 0);
            int commentCount = data.getIntExtra(Constant.COMMENT_COUNT, 0);
            articles.get(clickPosition).setLikeCount(likeCount);
            articles.get(clickPosition).setCommentCount(commentCount);
            articleAdapter.notifyItemChanged(clickPosition);
        }
    }

    @Override
    protected void initData() {
        setPresenter(new PenpalPresenter(getActivity()), this);
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.getRecommendPenpalList();
        presenter.getAriticleList(articlePageIndex, articlePageSize);
    }

    @OnClick({R.id.head_search, R.id.head_creat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_search:
                presenter.toSearchPenpal();
                break;
            case R.id.head_creat:
                if (UserInfoUtils.getUserInfo() != null) {
                    presenter.createPenpalPermission();
                } else {
                    LoginUtils.toLogin(getActivity());
                }
                break;
        }
    }

    @Override
    public void callBackPenpalList(PenpalHomeResponse response) {
        list.clear();
        list.add(new PenpalHomeResponse.ResponseBean.RecommendPenpalwillBean());
        if (response != null) {
            PenpalHomeResponse.ResponseBean.RecommendPenpalwillBean mePenpalwill = response.getResponse().getMePenpalwill();
            if (mePenpalwill != null) {
                mePenpalwill.setIsCreator(true);
                list.add(mePenpalwill);
            }
            list.addAll(response.getResponse().getRecommendPenpalwill());
            penpalAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void callBackArticles(PenpalRecommendArticleResponse response) {
        if (articlePageIndex == 1) {
            articles.clear();
        }
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadmore();
        }
        articles.addAll(response.getResponse());
        articleAdapter.notifyDataSetChanged();
        if (response.getResponse().size() == 0) {
            refreshLayout.setLoadmoreFinished(true);
        }
    }
}
